<template>
	<xn-form-container title="质检详情" width="90%" :visible="visible" :destroy-on-close="true" @close="onClose">
		<spin>
			<a-row :gutter="[10, 0]" class="custom-row" style="height: 5vh">
				<a-col :span="16">
					<AudioPlayer :audio-url="audioUrl" width="98%" height="90%" />
				</a-col>
				<div style="margin-right: 10px">
					<a-button type="primary" @click="showModal" style="margin-left: 10px">质检审核</a-button>
					<br />
					<a-modal v-model:open="open" title="质检审核" @ok="handleOPen" :footer="null">
						<a-descriptions size="small" bordered style="text-align: left">
							<a-descriptions-item label="审核状态" :span="24" style="text-align: left">
								<a-select
									v-model:value="qualityFormData.qualityApproveStatus"
									:disabled="qualityApproveDisabled"
									style="width: 40%"
									placeholder="请选择问题方"
									:options="voiceCheckStatusOptions"
								/>
							</a-descriptions-item>
							<a-descriptions-item label="审核备注" :span="24">
								<a-textarea
									v-model:value="qualityFormData.qualityApproveRemark"
									:disabled="qualityApproveDisabled"
									placeholder="请输入审核备注"
									:auto-size="{ minRows: 4, maxRows: 8 }"
								/>
							</a-descriptions-item>
						</a-descriptions>
						<div style="display: flex; justify-content: flex-end; margin-top: 15px">
							<a-button type="dashed" @click="closeCard" style="margin-right: 10px">取消</a-button>
							<a-button
								type="primary"
								v-if="!qualityApproveDisabled && hasPerm('violationQualityApproveBtn')"
								:loading="saveApproveStatusLoading"
								@click="saveApproveStatus('quality')"
							>
								保存
							</a-button>
						</div>
					</a-modal>
				</div>
				<div>
					<a-button type="primary" @click="showModal1">主管审核</a-button>
					<br />
					<a-modal v-model:open="open1" title="质检审核" @ok="handleOPen1" :footer="null">
						<a-descriptions title="主管审核" size="small" bordered style="text-align: left">
							<a-descriptions-item label="审核状态" :span="24">
								<a-select
									v-model:value="supervisorFormData.supervisorApproveStatus"
									:disabled="supervisorApproveDisabled"
									style="width: 40%"
									placeholder="请选择问题方"
									:options="voiceCheckStatusOptions"
								/>
								<a-button
									class="ml-4"
									type="primary"
									danger
									@click="modalVisible = true"
									v-if="
										(supervisorFormData.supervisorApproveStatus === '1' ||
											supervisorFormData.supervisorApproveStatus === '3') &&
										!supervisorApproveDisabled
									"
								>
									客户拉黑
								</a-button>
							</a-descriptions-item>
							<a-descriptions-item label="审核备注" :span="24">
								<a-textarea
									v-model:value="supervisorFormData.supervisorApproveRemark"
									:disabled="supervisorApproveDisabled"
									placeholder="请输入审核备注"
									:auto-size="{ minRows: 4, maxRows: 8 }"
								/>
							</a-descriptions-item>
						</a-descriptions>
						<div style="display: flex; justify-content: flex-end; margin-top: 15px">
							<a-button type="dashed" @click="closeCard1" style="margin-right: 10px">取消</a-button>
							<a-button
								type="primary"
								v-if="!supervisorApproveDisabled && hasPerm('violationSupervisorApproveBtn')"
								:loading="saveApproveStatusLoading"
								@click="saveApproveStatus('supervisor')"
								>保存
							</a-button>
						</div>
					</a-modal>
				</div>
			</a-row>
			<a-row :gutter="[10, 10]" class="custom-row" style="height: 20%">
				<a-col :span="16">
					<a-card
						:bordered="false"
						class="monitor-center-row-col-card"
						style="--antd-card-head-height: 0; overflow: hidden; height: 16.5vh"
					>
						<a-descriptions
							title="话单详情"
							size="small"
							layout="horizontal"
							bordered
							style="--descriptions-title-margin-bottom: 0px; --descriptions-item-padding-vertical: 0px"
						>
							<a-descriptions-item label="通话序列号">{{ callRecord.callId }}</a-descriptions-item>
							<a-descriptions-item label="被叫">{{ callRecord.callee }}</a-descriptions-item>
							<a-descriptions-item label="通话类型">{{ callRecord.callTypeName }}</a-descriptions-item>
							<a-descriptions-item label="所属公司">{{ callRecord.deptName }}</a-descriptions-item>
							<a-descriptions-item label="坐席账号">{{ callRecord.agentNum }}</a-descriptions-item>
							<a-descriptions-item label="坐席姓名">{{ callRecord.userName }}</a-descriptions-item>
						</a-descriptions>
					</a-card>
				</a-col>
				<a-col :span="8">
					<a-card :bordered="false" class="monitor-center-row-col-card custom-card" style="height: 16.5vh">
						<h3>命中关键字</h3>
						<CiYunTu03 :callId="callId" />
					</a-card>
					<br />
				</a-col>
			</a-row>
			<a-row :gutter="10" class="custom-row">
				<a-col :span="16">
					<div class="lb-box" :style="{ height: '60vh', 'background-color': 'white' }">
						<!-- 原来的聊天记录 -->
						<!--					<div-->
						<!--						v-for="(message, index) in messageList"-->
						<!--						:key="index"-->
						<!--						:class="['message', message.speakerRole === 1 ? 'position-left' : 'position-right']"-->
						<!--					>-->
						<!--						<div :class="['message-header', message.speakerRole === 1 ? 'user-header' : 'sys-header']">-->
						<!--							{{-->
						<!--								message.speakerRole === 1 ? '客户' : '坐席'-->
						<!--							}}&nbsp;&nbsp;&nbsp;&nbsp;{{ message.chatTime }}-->
						<!--						</div>-->
						<!--						<div-->
						<!--							style="white-space: pre-line;"-->
						<!--							:class="['message-content', message.speakerRole === 1 ? 'user-text-box' : 'sys-text-box']"-->
						<!--						>-->
						<!--							<div v-html="message.content"></div>-->
						<!--						</div>-->
						<!--					</div>-->
						<!-- 仿微信聊天记录 -->
						<ChatWindow :current-user="currentUser" :target-user="targetUser" :messages="messages" />
					</div>
				</a-col>
				<a-col :span="8">
					<a-card
						title="AI 推理过程"
						:bordered="false"
						class="monitor-center-row-col-card lb-box"
						style="height: 60vh; overflow-y: auto"
					>
						{{ aiReason }}
					</a-card>
				</a-col>
			</a-row>
		</spin>
	</xn-form-container>
</template>

<script setup>
	import { computed } from 'vue'
	import voiceTextApi from '@/api/qc/voice/text/voiceTextApi'
	import htApi from '@/api/tjzy/call/ht/htApi'
	import callReceiptApi from '@/api/tjzy/call/receipt/callReceiptApi'
	import tool from '@/utils/tool'
	import voiceCheckApi from '@/api/qc/voice/check/voiceCheckApi'
	import { required } from '@/utils/formRules'
	import complaintApi from '@/api/tjzy/complaint/complaintApi'
	import CiYunTu03 from '@/views/qc/voice/check/CiYunTu03.vue'
	import AudioPlayer from '@/views/qc/voice/check/AudioPlayer.vue'
	//仿微信聊天记录
	import { ref } from 'vue'
	import ChatWindow from '@/views/qc/voice/chat/ChatWindow.vue'
	import dayjs from 'dayjs'
	// 在父组件中调用示例
	const messageListRef = ref(null)

	// 模拟数据
	const currentUser = reactive({
		id: 1,
		name: '客服',
		avatar: new URL('@/assets/images/service_avatar.png', import.meta.url).href
	})

	const targetUser = reactive({
		id: 2,
		name: '客户',
		avatar: new URL('@/assets/images/customer_avatar.png', import.meta.url).href
	})

	const messages = ref([])

	const emit = defineEmits({ successful: null })
	const visible = ref(false)
	const audioUrl = ref()
	const aiReason = ref()
	const spinning = ref(false)

	const isStop = ref(false)
	const messageList = ref([])
	const callRecord = ref({
		callId: undefined,
		callee: undefined,
		agentNum: undefined,
		userName: undefined,
		companyName: undefined,
		callTypeName: undefined
	})

	const saveApproveStatusLoading = ref(false)

	const qualityFormData = ref({
		id: undefined,
		qualityApproveStatus: undefined,
		qualityApproveRemark: undefined
	})
	const qualityApproveDisabled = ref(false)

	const supervisorFormData = ref({
		id: undefined,
		supervisorApproveStatus: undefined,
		supervisorApproveRemark: undefined
	})
	const supervisorApproveDisabled = ref(false)

	const voiceCheckStatusOptions = tool.dictList('voiceCheckStatus')
	const complaintsImportanceOptions = tool.dictList('complaintsImportance')

	const headerHeight = 120
	const footerHeight = 60
	const calcAiBoxHeight = computed(() => {
		return `calc(100vh - ${114}px)`
	})
	const calcLeftBoxHeight = computed(() => {
		return `calc(100vh - ${headerHeight + footerHeight}px)`
	})

	const resetProject = ref(false)
	const modalVisible = ref(false)
	const modalFormRef = ref()
	const modalFormData = ref({
		mobile: undefined,
		complainImportant: undefined,
		projectCode: undefined,
		complainContent: undefined
	})
	const modalFormRules = {
		complainImportant: [required('请选择重要程度')],
		projectCode: [required('请选择所属项目')],
		complainContent: [required('请输入投诉内容')]
	}
	const callId = ref()
	// 打开抽屉
	const onOpen = (record) => {
		spinning.value = true
		setFormData(record)
		modalFormData.value.mobile = record.liaisonPhone
		visible.value = true
		audioUrl.value = record.fileUrl
		aiReason.value = record.aiReasonContent
		callId.value = record.callId
		// console.log(record)
		//查询语音文本
		voiceTextApi.getTextByCallId(record.callId).then((res) => {
			//原来的聊天记录
			// messageList.value = res;
			//仿微信聊天记录
			messages.value = []
			//把res转化成messages
			res.forEach((item) => {
				// console.log('聊天内容 -> ',item)
				messages.value.push({
					id: item.id,
					content: item.content,
					timestamp: item.chatTime,
					isSelf: item.speakerRole === 2
				})
			})
		})

		//查询话单
		// htApi.callRecordPage({
		// 	current: 1,
		// 	size: 1,
		// 	beginTime: '2024-10-01 00:00:00',
		// 	endTime: '2026-02-26 23:59:59',
		// 	callId: record.callId
		// }).then(res => {
		// 	console.log('rrrr',res);
		// 	if (res && res.records && res.records[0]) {
		// 		callRecord.value = res.records[0];
		// 		callRecord.value.userName = record.userName;
		// 		callRecord.value.deptName = record.deptName;
		// 	} else {
		// 		callRecord.value.userName = '';
		// 		callRecord.value.deptName = '';
		// 	}
		// })

		// 查询话单
		callReceiptApi
			.pageList({
				current: 1,
				size: 1,
				beginTime: '2024-10-01 00:00:00',
				endTime: `${dayjs().format('YYYY-MM-DD')} 23:59:59`,
				callId: record.callId
			})
			.then((res) => {
				// console.log('rrrr', res)
				if (res && res.records && res.records[0]) {
					callRecord.value = res.records[0]
				} else {
					callRecord.value.userName = ''
					callRecord.value.companyName = ''
				}
			})
	}

	// 关闭抽屉
	const onClose = () => {
		visible.value = false
		stopAudio()
	}

	// 停止音频播放
	const stopAudio = () => {
		isStop.value = true
		setTimeout(() => {
			isStop.value = false
		}, 500)
	}

	const setFormData = (record) => {
		qualityFormData.value.id = record.id
		qualityFormData.value.qualityApproveStatus = record.qualityApproveStatus
		qualityFormData.value.qualityApproveRemark = record.qualityApproveRemark
		qualityApproveDisabled.value = record.qualityApproveStatus != null && record.qualityApproveStatus > 0
		supervisorFormData.value.id = record.id
		supervisorFormData.value.supervisorApproveStatus = record.supervisorApproveStatus
		supervisorFormData.value.supervisorApproveRemark = record.supervisorApproveRemark
		supervisorApproveDisabled.value = record.supervisorApproveStatus != null && record.supervisorApproveStatus > 0
	}

	const saveApproveStatus = (type) => {
		saveApproveStatusLoading.value = true
		let obj = {}
		if (type === 'quality') {
			obj = qualityFormData.value
		}
		if (type === 'supervisor') {
			obj = supervisorFormData.value
		}
		voiceCheckApi.modifyViolationStatus(obj).then((res) => {
			onClose()
			emit('successful')
			saveApproveStatusLoading.value = false
		})
	}

	const changeCompanySelectEvent = (val) => {
		modalFormData.value.projectCode = val.projectCode
	}

	const handleOk = () => {
		complaintApi.blackoutCustomers(modalFormData.value).finally((res) => {
			handleClose()
		})
	}

	const handleClose = () => {
		modalFormRef.value.resetFields()
		resetProject.value = true
		setTimeout(() => {
			resetProject.value = false
		}, 200)
		modalVisible.value = false
	}
	//以下是新加的
	const open = ref(false)
	const showModal = () => {
		open.value = true
	}
	const closeCard = () => {
		open.value = false
	}
	const handleOPen = (e) => {
		console.log(e)
		open.value = false
	}
	const open1 = ref(false)
	const showModal1 = () => {
		open1.value = true
	}
	const handleOPen1 = (e) => {
		console.log(e)
		open1.value = false
	}
	const closeCard1 = () => {
		open1.value = false
	}
	// 暴露方法供父组件调用
	defineExpose({
		onOpen
	})
</script>

<style scoped>
	.lb-box {
		overflow-y: auto;
		padding: 10px;
		border: 1px solid #ccc;
	}

	.message {
		margin-bottom: 10px;
	}

	.position-left {
		text-align: left;
		margin-right: auto;
	}

	.position-right {
		text-align: right;
		margin-left: auto;
	}

	.sys-header {
		color: #1890ff;
	}

	.user-header {
		color: #1890ff;
	}

	.sys-text-box {
		background-color: #00ff80;
		max-width: 100%;
		margin-left: auto;
		border-radius: 5px;
		padding: 5px;
	}

	.user-text-box {
		background-color: #ffffff;
		border: 1px solid #ddd;
		max-width: 100%;
		margin-right: auto;
		border-radius: 5px;
		padding: 5px;
	}

	/* 自定义滚动条样式 */
	.lb-box::-webkit-scrollbar {
		width: 8px;
	}

	.lb-box::-webkit-scrollbar-track {
		background: #f1f1f1;
	}

	.lb-box::-webkit-scrollbar-thumb {
		background: #888;
		border-radius: 4px;
	}

	.lb-box::-webkit-scrollbar-thumb:hover {
		background: #555;
	}

	.monitor-center-row-col-card {
		text-align: center;
	}

	:deep(.ant-descriptions-title) {
		margin-bottom: var(--descriptions-title-margin-bottom, 0px); /* 减少 title 下方的间距 */
	}

	:deep(.ant-descriptions-item) {
		padding-top: var(--descriptions-item-padding-vertical, 0px); /* 减少每个描述项的垂直内边距 */
		padding-bottom: var(--descriptions-item-padding-vertical, 0px);
	}

	/* 穿透样式作用域，修改 .ant-card-head 的样式 */
	:deep(.ant-card-head) {
		/* 减少 title 部分的上下内边距，默认值较大，这里缩小为 5px */
		padding: 0px 0;
		/* 减少 title 与卡片上边框的距离，将外边距底部设为 2px */
		margin-bottom: 0px;
	}

	/* 穿透样式作用域，修改 .ant-card-head-title 的样式 */
	/* 穿透样式作用域，修改 .ant-card-body 的样式 */
	:deep(.ant-card-body) {
		/* 减少正文部分的上下内边距，默认值较大，这里缩小为 8px */
		padding: 4px;
	}

	/* 穿透样式作用域，修改 .ant-card-head-title 的样式 */
	:deep(.ant-card-head-title) {
		/* 可以进一步调整 title 文字的行高，让其在垂直方向上更紧凑 */
		line-height: 0;
	}

	.custom-row {
		background-color: #f5f5f5; /* 设置间隔颜色，这里是红色 */
		padding: 10px; /* 与 gutter 的一半间隔一致 */
		margin-bottom: 0; /* 确保没有额外的下边距 */
	}

	.custom-audio {
		width: 100px; /* 或者指定一个固定宽度如 '500px' */
		height: auto; /* 自动高度适应内容 */
	}

	.custom-card .ant-card-body {
		padding-top: 0; /* 让内容靠近上边框 */
	}

	:deep(.ant-descriptions-item-label) {
		width: 104px; /* 设置固定宽度，可以根据实际需求调整 */
		flex: none; /* 防止宽度被弹性布局影响 */
	}
	:deep(.highlight) {
		background-color: red !important;
	}
</style>
